﻿using FastEventBus.Attribute;
using FastEventBus.Definition;
using FastEventBus.Entity;
using FastEventBus.Exception;
using System;
using System.Collections.Generic;
using System.Text;

namespace FastEventBus.Realization
{
    public class MemoryEventStroage : IFastEventStroage
    {
        public Dictionary<string, List<IFastEventHandler>> HandlerDic = new Dictionary<string, List<IFastEventHandler>>();
        public Dictionary<string,Dictionary<string, FastEventParam>> ParamDic = new Dictionary<string, Dictionary<string, FastEventParam>>();
        public void RegistHandler(IFastEventHandler Handler)
        {
            FastEventChannel Channel = System.Attribute.GetCustomAttribute(Handler.GetType(), typeof(FastEventChannel)) as FastEventChannel;
            if (Channel != null && !string.IsNullOrEmpty(Channel.ChannelName))
            {
                if (!HandlerDic.ContainsKey(Channel.ChannelName))
                {
                    List<IFastEventHandler> HandlerList = new List<IFastEventHandler>();
                    HandlerList.Add(Handler);
                    HandlerDic.Add(Channel.ChannelName, HandlerList);
                }
                else
                {
                    List<IFastEventHandler> HandlerList = HandlerDic[Channel.ChannelName];
                    HandlerList.Add(Handler);
                    HandlerDic[Channel.ChannelName] = HandlerList;
                }
            }
            else
            {
                throw new EventHandlerDefineExcption(string.Format("事件处理类{0}未正确声明Channel", Handler.GetType().FullName));
            }
        }

        public List<IFastEventHandler> ResolveHandler(string ChannelName)
        {
            return HandlerDic[ChannelName];
        }


        public void WriteEvent(FastEventParam Param)
        {
            if (!ParamDic.ContainsKey(Param.ChannelName))
            {
                Dictionary<string, FastEventParam> Dic = new Dictionary<string, FastEventParam>();
                Dic.Add(Param.EventID, Param);
                ParamDic.Add(Param.ChannelName, Dic);
            }
            else
            {
                ParamDic[Param.ChannelName].Add(Param.EventID, Param);
            }
        }

        public FastEventParam ReadEvent(string ChannelName,string EventID)
        {
            return ParamDic[ChannelName][EventID];
        }

        public void ACKEvent(string ChannelName,string EventID)
        {
            ParamDic[ChannelName].Remove(EventID);
        }
    }
}
